package com.exchange.util;

import com.jfinal.json.FastJson;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;

import javax.servlet.http.HttpServletRequest;
import java.net.UnknownHostException;
import java.util.Map;

public class IpUtil {
    /**
     * 获取ip地址信息
     *
     * @return
     * @throws UnknownHostException
     */
    public static Map<String, Object> getAddress(String ip) throws UnknownHostException {
        String returnStr = HttpKit.get("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
        Map<String, Object> result = FastJson.getJson().parse(returnStr, Map.class);
        result.put("ip", ip);
        if (0 == Integer.parseInt(result.get("code").toString())) {
            return (Map<String, Object>) result.get("data");
        } else {
            result.put("result", false);
            return result;
        }
    }
    /**
     * 获取访问用户的客户端IP（适用于公网与局域网）.
     */
    public static final String getIpAddr(final HttpServletRequest request)
            throws Exception {
        if (request == null) {
            throw (new Exception("getIpAddr method HttpServletRequest Object is null"));
        }
        String ipString = request.getHeader("x-forwarded-for");
        if (StrKit.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
            ipString = request.getHeader("Proxy-Client-IP");
        }
        if (StrKit.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
            ipString = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StrKit.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
            ipString = request.getRemoteAddr();
        }
        if (StrKit.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
        	ipString = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StrKit.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
        	ipString = request.getHeader("HTTP_X_FORWARDED_FOR");
        }

        // 多个路由时，取第一个非unknown的ip
        final String[] arr = ipString.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ipString = str;
                break;
            }
        }

        return ipString;
    }
}